package org.sys.transporttrainsys.service;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.sys.transporttrainsys.dto.ExamStatistics;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

@Service
public class ReportService {

    public void generateExcelReport(List<ExamStatistics> statistics, String fileName) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Exam Statistics Report");

        // Create header row
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("考试ID");
        headerRow.createCell(1).setCellValue("考试名称");
        headerRow.createCell(2).setCellValue("平均分");
        headerRow.createCell(3).setCellValue("通过率 (%)");
        headerRow.createCell(4).setCellValue("总尝试次数");
        headerRow.createCell(5).setCellValue("总通过次数");

        // Fill data rows
        int rowNum = 1;
        for (ExamStatistics stat : statistics) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(stat.getExamId());
            row.createCell(1).setCellValue(stat.getExamName());
            row.createCell(2).setCellValue(stat.getAverageScore());
            row.createCell(3).setCellValue(stat.getPassRate());
            row.createCell(4).setCellValue(stat.getTotalAttempts());
            row.createCell(5).setCellValue(stat.getTotalPassed());
        }

        // Write to file
        try (FileOutputStream fileOut = new FileOutputStream(fileName)) {
            workbook.write(fileOut);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}